package com.zmyuan.demo.netty.websocket.socket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * Created by zdb on 2017/2/16.
 */
public class ChatRoomHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String context = msg.text();
        for(Channel channel : group) {
            if(channel != ctx.channel()) {
                channel.writeAndFlush(wrap(ctx.channel().remoteAddress() + ":" + context));
            } else {
                channel.writeAndFlush(wrap("服务端返回:" + context));
            }
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        for(Channel c : group) {
            c.writeAndFlush(wrap(ctx.channel().remoteAddress() + "用户加入聊天室"));
        }
        group.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        for(Channel c : group) {
            c.writeAndFlush(wrap(ctx.channel().remoteAddress() + "用户离开聊天室"));
        }
        group.remove(ctx.channel());
    }

    private TextWebSocketFrame wrap(String msg) {
        return new TextWebSocketFrame(msg);
    }
}
